from fastapi import APIRouter, Depends
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from app.db.database import get_db
from app.core.security import check_admin_permission, get_current_user
from app.core.exceptions import (
    DataNotFoundError,
    SignUpLimitError,
    DuplicateSignUpError
)
from app.models.form import Form, FormSubmission
from app.models.post import Activity
from app.schemas.form import (
    FormCreate,
    Form as FormSchema,
    FormSubmissionCreate,
    FormSubmission as FormSubmissionSchema
)
from app.schemas.user import TokenData

router = APIRouter(prefix="/activity/form", tags=["表单"])

@router.post("/create", status_code=201)
async def create_form(
    form: FormCreate,
    current_user: TokenData = Depends(check_admin_permission),
    db: AsyncSession = Depends(get_db)
):
    # 检查活动是否存在
    result = await db.execute(
        select(Activity).where(Activity.id == form.activity_id)
    )
    activity = result.scalar_one_or_none()
    
    if not activity:
        raise DataNotFoundError("活动不存在")
    
    # 创建表单
    db_form = Form(**form.dict())
    db.add(db_form)
    await db.commit()
    
    return {"code": 10000, "data": "success"}

@router.get("/{activity_id}", response_model=FormSchema)
async def get_form(
    activity_id: int,
    db: AsyncSession = Depends(get_db)
):
    result = await db.execute(
        select(Form).where(Form.activity_id == activity_id)
    )
    form = result.scalar_one_or_none()
    
    if not form:
        raise DataNotFoundError()
    
    return form

@router.post("/fill", status_code=201)
async def fill_form(
    submission: FormSubmissionCreate,
    current_user: TokenData = Depends(get_current_user),
    db: AsyncSession = Depends(get_db)
):
    # 检查活动是否存在
    result = await db.execute(
        select(Activity).where(Activity.id == submission.activity_id)
    )
    activity = result.scalar_one_or_none()
    
    if not activity:
        raise DataNotFoundError("活动不存在")
    
    # 检查是否已达到人数限制
    if activity.count_limit > 0 and activity.current_count >= activity.count_limit:
        raise SignUpLimitError()
    
    # 检查是否已经报名
    result = await db.execute(
        select(FormSubmission)
        .join(Form)
        .where(
            Form.activity_id == submission.activity_id,
            FormSubmission.user_id == current_user.id
        )
    )
    if result.scalar_one_or_none():
        raise DuplicateSignUpError()
    
    # 获取表单
    result = await db.execute(
        select(Form).where(Form.activity_id == submission.activity_id)
    )
    form = result.scalar_one_or_none()
    
    if not form:
        raise DataNotFoundError("表单不存在")
    
    # 创建提交记录
    db_submission = FormSubmission(
        form_id=form.id,
        user_id=current_user.id,
        answers=submission.answers
    )
    db.add(db_submission)
    
    # 更新活动报名人数
    activity.current_count += 1
    
    await db.commit()
    
    return {"code": 10000, "data": "报名成功"}

@router.get("/{activity_id}/isSignUp")
async def check_sign_up(
    activity_id: int,
    current_user: TokenData = Depends(get_current_user),
    db: AsyncSession = Depends(get_db)
):
    result = await db.execute(
        select(FormSubmission)
        .join(Form)
        .where(
            Form.activity_id == activity_id,
            FormSubmission.user_id == current_user.id
        )
    )
    is_signed_up = result.scalar_one_or_none() is not None
    
    return {"code": 10000, "data": is_signed_up}

@router.get("/{activity_id}/success")
async def get_sign_up_success(
    activity_id: int,
    current_user: TokenData = Depends(get_current_user),
    db: AsyncSession = Depends(get_db)
):
    result = await db.execute(
        select(Activity).where(Activity.id == activity_id)
    )
    activity = result.scalar_one_or_none()
    
    if not activity:
        raise DataNotFoundError()
    
    success_message = f"您已成功报名 {activity.name}"
    return {"code": 10000, "data": success_message} 